package com.psp.stock.controller;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateBetween;
import cn.hutool.core.date.DateUnit;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.psp.stockinterface.service.IStockInterfaceService;
import com.psp.util.StockUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.psp.stock.domain.Stock;
import com.psp.stock.service.IStockService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 股票基础信息Controller
 *
 * @author psp
 */
@RestController
@RequestMapping("/eye/stock")
public class StockController extends BaseController {
    @Resource
    private IStockService stockService;

    @Resource
    private IStockInterfaceService stockInterfaceService;

    /**
     * 查询股票基础信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Stock stock) {
        startPage();
        List<Stock> list = stockService.selectStockList(stock);
        return getDataTable(list);
    }

    /**
     * 从第三方接口更新所有的股票信息
     */
    @GetMapping("/updateAllStockInfoFromAPI")
    public AjaxResult updateAllStockInfoFromAPI() {
        logger.info("从第三方接口更新所有的股票信息-> 开始");
        Date s = new Date();
        List<Stock> remoteList = new LinkedList<>();
        List<Map<String, String>> mapList;
        try {
            String result = HttpUtil.get(stockInterfaceService.selectStockInterfaceById("1").getUrl());
            mapList = JSON.parseArray(result, (Type) Map.class);
            if (mapList == null || mapList.size() == 0 || mapList.get(0).get("dm") == null) {
                return AjaxResult.error();
            }
            for (Map<String, String> map : mapList) {
                Stock stock = new Stock();
                stock.setStockCode(map.get("dm"));
                stock.setStockName(map.get("mc"));
                stock.setStockExchange(map.get("jys"));
                if (map.get("dm").startsWith("688")) {
                    // 去除科创版股票以688开头
                    continue;
                }
                if ("sh".equalsIgnoreCase(map.get("jys")) || "sz".equalsIgnoreCase(map.get("jys"))) {
                    // 只获取交易所是sh和sz的股票
                    remoteList.add(stock);
                }
            }
        } catch (Exception e) {
            return AjaxResult.error();
        }

        // 获取数据库的所有股票
        List<Stock> dbList = stockService.selectStockListExcludeFund();
        // 数据库中不存在的股票,加入新增列表
        List<Stock> insertList = remoteList.stream().filter(a -> dbList.stream().noneMatch(b -> b.getStockCode().equals(a.getStockCode()))).collect(Collectors.toList());

        // 当前日期从新浪获取到的股票价格没有值的过滤掉
        for (int i = insertList.size() - 1; i >= 0; i--) {
            String[] price = StockUtils.getStockPriceBySina(insertList.get(i).getStockExchange() + insertList.get(i).getStockCode());
            if (price == null) {
                insertList.remove(i);
            } else {
                if (price[0].compareTo(LocalDate.now().toString()) < 0) {
                    insertList.remove(i);
                }
            }
        }
        stockService.batchInsertOrUpdate(insertList);

        // 数据库中存在,api获取的列表不存在,加入删除列表
        List<Stock> deleteList = dbList.stream().filter(a -> remoteList.stream().noneMatch(b -> b.getStockCode().equals(a.getStockCode()))).collect(Collectors.toList());
        if (deleteList.size() > 0) {
            stockService.deleteStockByIds(deleteList.stream().map(Stock::getId).toArray(String[]::new));
        }

        logger.info("从第三方接口更新所有的股票信息-> 结束");
        logger.info("用时:" + new DateBetween(s, new Date()).between(DateUnit.SECOND));
        return AjaxResult.success();
    }

    @GetMapping("/testUpdateAllStockAPI")
    public AjaxResult testUpdateAllStockAPI() {
        List<Map<String, String>> mapList;
        try {
            String result = HttpUtil.get(stockInterfaceService.selectStockInterfaceById("1").getUrl());
            mapList = JSON.parseArray(result, (Type) Map.class);
            mapList = mapList.subList(0, 10);
        } catch (Exception e) {
            return AjaxResult.error();
        }
        return AjaxResult.success(mapList);
    }

    /**
     * 获取股票基础信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(stockService.selectStockById(id));
    }

    /**
     * 新增股票基础信息
     */
    @Log(title = "股票基础信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Stock stock) {
        return toAjax(stockService.insertStock(stock));
    }

    /**
     * 修改股票基础信息
     */
    @Log(title = "股票基础信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Stock stock) {
        return toAjax(stockService.updateStock(stock));
    }

    /**
     * 删除股票基础信息
     */
    @Log(title = "股票基础信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(stockService.deleteStockByIds(ids));
    }

    /**
     * 清空股票数据
     */
    @DeleteMapping("/clearStockData")
    public AjaxResult clearStockData() {
        stockService.clearStockData();
        return AjaxResult.success();
    }

    /**
     * 导出股票基础信息列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, Stock stock) {
        List<Stock> list = stockService.selectStockList(stock);
        ExcelUtil<Stock> util = new ExcelUtil<>(Stock.class);
        util.exportExcel(response, list, "股票基础信息数据");
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        List<Stock> list = new ArrayList<>();
        Stock stock = new Stock();
        stock.setStockExchange("上交所写sh,深交所sz");
        stock.setListingDate("字符串即可");
        list.add(stock);
        ExcelUtil<Stock> util = new ExcelUtil<>(Stock.class);
        util.exportExcel(response, list, "股票模板");
    }

    /**
     * 导入股票信息
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Stock> util = new ExcelUtil<>(Stock.class);
        List<Stock> exportList = util.importExcel(file.getInputStream());
        logger.info("获取数据总条数:{}", exportList.size());
        stockService.batchInsertOrUpdate(exportList);
        return AjaxResult.success();
    }

}
